package com.atguigu.jxc.aspect;

import com.atguigu.jxc.annotation.Log;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @ClassName:LogAspect
 * @Version: 1.0
 * @CreateAt:2021/3/8 14:55
 * @Author: ✨HanSan·胡✨
 * @Description:   自定义日志切面类
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogService logService;

    /**
     * @Description: //TODO 切入点是注解方式，也可以使用节点表达式包名方式 效果一样。
     * @Param: []
     * @return: void
     * @Version: 1.0
     * @Date: 2021/3/8 15:02
     * @Author: HanSan·胡
     **/
    @Pointcut("@annotation(com.atguigu.jxc.annotation.Log)")
    public void log(){}

    @Around("log()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object res = null;
        long time = System.currentTimeMillis();
        try {
            res =  joinPoint.proceed();
            time = System.currentTimeMillis() - time;
            return res;
        } finally {
            try {
                //方法执行完成后增加日志
                addLog(joinPoint,res,time);
            }catch (Exception e){
                System.out.println("LogAspect 操作失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private void addLog(ProceedingJoinPoint joinPoint, Object res, long time) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpSession session = null;
        if(requestAttributes!=null){
             session = (HttpSession)requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION);
        }
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        com.atguigu.jxc.entity.Log log = new com.atguigu.jxc.entity.Log();

        Log logAnnotation = signature.getMethod().getAnnotation(Log.class);
        if(logAnnotation != null){
            log.setLogType(logAnnotation.logType());
            log.setContent(logAnnotation.logContent());
            log.setLogDate(new Date());
            User user = (User) session.getAttribute("currentUser");
            log.setUserId(user.getUserId());
            logService.save(log);
        }
        //TODO 这里保存日志
        System.out.println("记录日志:" + log.toString());
//        operationLogService.insert(operationLog);
    }


}
